﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinThreadTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TakeBath();
            Task task1 = new Task(new Action(() => CookRice()));
            task1.Start();

            Task task2 = new Task(new Action(() => Cleanup()));
            task2.Start();

            

            //List<Task> list = new List<Task>();

            //for (int i = 0; i < 3; i++)
            //{
            //    list.Add(new Task(new Action(()=> CookRice())));
            //}

            //for (int i = 0;i < list.Count; i++)
            //{
            //    var task = list[i];
            //    task.Start();
            //}
        }
        private async void TakeBath()
        {
            var num = await TakeBathAsync();
            WriteLog($"num = {num}");

            //return num;
        }
        private async Task<int> TakeBathAsync()
        {
            //WriteLog($"开始拿毛巾....");
            //Thread.Sleep(1000);
            WriteLog($"拿到毛巾了，准备洗澡....");
            var num = await Task.Run(() =>
            {
                Thread.Sleep(4000);
                WriteLog($"洗澡完成，花费8秒");
                return 200;
            });
            WriteLog($"输出num = {num}");
            return num;
        }

        private void CookRice()
        {
            WriteLog($"开始煮饭....");
            Thread.Sleep(5000);
            WriteLog($"煮饭完成，花费5秒");
        }
        private void Cleanup()
        {
            WriteLog($"开始打扫卫生....");
            Thread.Sleep(3000);
            WriteLog($"打扫卫生完成，花费3秒");
        }

        private void WriteLog(object obj)
        {
            this.Invoke(new Action(() =>
            {
                txtMsg.Text += $"{DateTime.Now.ToString("HH:mm:ss")} - {obj}\r\n";
            }));

        }
    }
}
